import React, {Component} from 'react';
import {Form, Input, Button, message} from 'antd';
import { LockOutlined } from '@ant-design/icons';
import {reqUpdateUser} from '../../api/user'
import store from "store";
import {withRouter} from 'react-router-dom';

// 修改密码表单
class ChangePwd extends Component {

  updateUser = async (values) => {
    const user = store.get('user');
    try {
      if (user) {
        const {data: res} = await reqUpdateUser(user.uid, {password: values.password});
        message.success(res.message);
        store.remove('token');
        this.props.history.replace('/admin/login');
      } else {
        message.error('登录失效', 1, () => {
          store.remove('token');
          window.location.href = '/admin/login';
        });
      }
    } catch (e) {
      message.error(e.data.name || e.data.message);
    }
  }

  onFinish = (values) => {
    this.updateUser(values);
  };

  render() {
    return (
      <Form
        name="normal_login"
        className="login-form"
        ref={instance => this.formRef = instance}
        onFinish={this.onFinish}
        wrapperCol={
          {xs: {span: 24}, sm: {span: 10}}
        }
      >
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
            {
              type: 'string',
              min: 6,
              max: 16,
              pattern: /^[0-9a-zA-Z]{1,}$/,
              message: '密码必须是6-16位字母、数字组成'
            }
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="请输入密码"
          />
        </Form.Item>
        <Form.Item
          name="password1"
          dependencies={['password']}
          hasFeedback
          rules={[
            {
              required: true,
              message: '请再次输入密码',
            },
            {
              type: 'string',
              min: 6,
              max: 16,
              pattern: /^[0-9a-zA-Z]{1,}$/,
              message: '密码必须是6-16位字母、数字组成'
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject('两次密码不一致');
              },
            }),
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="请再次输入密码"
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            提交
          </Button>
        </Form.Item>
      </Form>
    )
  }
}

export default withRouter(ChangePwd);
